package win.ganbo.softwareFive.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis操作工具类
 *                       
 * @Filename: RedisUtil.java
 * @Version: 1.0
 * @Author: 吕鹏
 * @Email: lvpeng@gyidragon.com
 *
 */
public class RedisUtil {
    protected static Logger  LOGGER            = Logger.getLogger(RedisUtil.class);
    private static RedisUtil singleton;
    private final String     LOCAL_SESSION_KEY = "LOCAL_SESSION_KEY";

    private JedisPool        jedisPool         = null;

    /**
     * redis过期时间,以秒为单位
     */
    public final static int  EXRP_HOUR         = 60 * 60;                          // 一小时
    public final static int  EXRP_DAY          = 60 * 60 * 24;                     // 一天
    public final static int  EXRP_MONTH        = 60 * 60 * 24 * 30;                // 一个月

    public static RedisUtil getSingleton() {
        if (singleton == null) {
            synchronized (RedisUtil.class) {
                if (singleton == null) {
                    singleton = new RedisUtil();
                    return singleton;
                }
            }
        }
        return singleton;
    }

    /**
     * 初始化Redis连接池
     */
    private synchronized boolean initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(200);
            //            config.setMaxTotal(300);
            config.setTestOnBorrow(false);
            config.setTestOnReturn(false);
            jedisPool = new JedisPool(config, "175.25.186.57", 6379, 5000);
            return true;
        } catch (Exception e) {
            LOGGER.error("First create JedisPool error : " + e.toString());
        }
        return false;
    }

    /**
     * 在多线程环境同步初始化
     */
    private synchronized void poolInit() {
        if (jedisPool == null) {
            initialPool();
        }
    }

    /**
     * 同步获取Jedis实例
     * 
     * @return Jedis
     */
    public synchronized Jedis getJedis() {
        if (jedisPool == null) {
            poolInit();
        }
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            LOGGER.error("Get jedis error : " + e);
        }
        return jedis;
    }

    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.destroy();
        }
    }

    /**
     * 设置 String
     * 
     * @param key
     * @param value
     */
    public void setString(String key, String value) {
        try {
            value = StringUtils.isEmpty(value) ? "" : value;
            getJedis().set(key, value);
        } catch (Exception e) {
            LOGGER.error("Set key error : " + e);
        }
    }

    /**
     * 设置 过期时间
     * 
     * @param key
     * @param seconds
     *            以秒为单位
     * @param value
     */
    public void setString(String key, int seconds, String value) {
        try {
            value = StringUtils.isEmpty(value) ? "" : value;
            getJedis().setex(key, seconds, value);
        } catch (Exception e) {
            LOGGER.error("Set keyex error : " + e);
        }
    }

    /**
     * 获取String值
     * 
     * @param key
     * @return value
     */
    public String getString(String key) {
        if (getJedis() == null || !getJedis().exists(key)) {
            return null;
        }
        return getJedis().get(key);
    }

    /**
     * 删除
     * @param key
     * @param seconds
     * @param value
     */
    public void delString(String key) {
        try {
            getJedis().del(key);
        } catch (Exception e) {
            LOGGER.error("delString error : " + e);
        }
    }

    /**
     * 设置生命周期
     * @param key
     */
    public void setLifeCycleTime(String key, int expire) {
        try {
            getJedis().expire(key, expire);
        } catch (Exception e) {
            LOGGER.error("setLifeCycleTime error : " + e);
        }
    }

    /**
     * 设置 Map
     * 
     * @param key
     * @param value
     */
    public void setSessionMap(String key, String value) {
        try {
            getJedis().hset(LOCAL_SESSION_KEY, key, value);
        } catch (Exception e) {
            LOGGER.error("Set map key error : " + e);
        }
    }

    /**
     * 获取map值
     * 
     * @param key
     * @return value
     */
    public String getSessionMap(String key) {
        if (getJedis() == null) {
            return null;
        }
        return getJedis().hget(LOCAL_SESSION_KEY, key);
    }

    /**
     * 删除key
     * @param key
     */
    public void delSessionMap(String key) {
        try {
            getJedis().hdel(LOCAL_SESSION_KEY, key);
        } catch (Exception e) {
            LOGGER.error("Set map key error : " + e);
        }
    }

    public JedisPool getJedisPool() {
        return this.jedisPool;
    }

    public static void main(String args[]) {
        RedisUtil.getSingleton().setString("33333_test1", "是的发送到收到收到1");
        RedisUtil.getSingleton().setString("33333_test2", "是的发送到收到收到2");
        RedisUtil.getSingleton().setString("33333_test3", "是的发送到收到收到3");
        RedisUtil.getSingleton().setString("33333_test4", "是的发送到收到收到4");
        System.out.println("完毕");
    }
}
